'''
@Description: In User Settings Edit
@Author: your name
@Date: 2019-09-25 09:48:29
@LastEditTime: 2019-12-06 12:35:50
@LastEditors: Please set LastEditors
'''
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.mongo_bill_service import MongoBillFilter
from ...service.buss_pub.bill_manage import BillManageService, TypeId, OperationType
from ...service.common import insert_data, find_data, update_data, delete_data, get_condition, get_info
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...pao_python.pao.service.security.security_service import RoleService
import hashlib
import re
import datetime
import uuid
import pandas as pd
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList
from ...service.common import get_current_role_id, get_current_user_id
'''
@Description: In User Settings Edit
@Author: your name
@Date: 2019-09-25 09:48:29
@LastEditTime: 2019-09-25 09:48:29
@LastEditors: your name
'''

# -*- coding: utf-8 -*-

'''
能力评估模板
'''


class AssessmentTemplateService(MongoService):
    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def get_assessment_template_list(self, org_list, condition, page, count):
        '''
            获取评估模板列表
            Arguments:
                condition   {dict}      条件
                page        {number}    页码
                count       {number}    条数
        '''
        if 'date_range' in list(condition.keys()):
            condition['start_date'] = condition['date_range'][0]
            condition['end_date'] = condition['date_range'][1]
        keys = ['id', 'template_name', 'state',
                'start_date', 'end_date', 'is_edit', 'template_type', 'describe']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id'])
                           & (C('state').like(values['state']))
                           & (C('describe').like(values['describe']))
                           & (C('create_date') >= as_date(values['start_date']))
                           & (C('create_date') <= as_date(values['end_date']))
                           & (C('template_name').like(values['template_name']))
                           & (C('template_type') == values['template_type'])
                           & (C('organization_id').inner(org_list)))
        if 'id' in list(condition.keys()) and 'is_edit' not in list(condition.keys()):
            # 这样表示查看评估记录模版内容时使用
            _filter.unwind('dataSource')\
                   .add_fields({'assessment_projects': '$dataSource.assessment_projects'})\
                   .lookup_bill('PT_Assessment_Project', 'assessment_projects', 'id', 'ass_info')\
                   .unwind('ass_info')\
                   .project({'_id': 0, 'assessment_projects': 1, 'ass_info': 1})\
                   .project({'ass_info._id': 0})
        else:
            # 这样表示编辑评估模版时使用
            _filter.project({'_id': 0})
        print(_filter.filter_objects)
        res = self.page_query(_filter, 'PT_Assessment_Template', page, count)
        return res

    def get_assessment_template_list_all_look(self, org_list, condition, page, count):
        '''
            获取评估模板列表
            Arguments:
                condition   {dict}      条件
                page        {number}    页码
                count       {number}    条数
        '''
        if 'date_range' in list(condition.keys()):
            condition['start_date'] = condition['date_range'][0]
            condition['end_date'] = condition['date_range'][1]
        keys = ['id', 'template_name', 'state',
                'start_date', 'end_date', 'is_edit', 'template_type']
        values = self.get_value(condition, keys)
        user_id = get_current_user_id(self.session)
        if 'dab486e2-d08d-11e9-90bb-144f8aec0be5' in org_list:
            _filter = MongoBillFilter()
            if values['template_type'] != '护理评估':
                _filter.match_bill((C('id') == "11c453d6-0d1b-11ea-ac6d-005056882303"))\
                    .project({'_id': 0})
                res = self.page_query(
                    _filter, 'PT_Assessment_Template', page, 1)
            else:
                _filter.match_bill((C('template_type') == "护理评估"))\
                    .project({'_id': 0})
                res = self.page_query(
                    _filter, 'PT_Assessment_Template', page, 10)
        else:
            _filter = MongoBillFilter()
            _filter.match_bill((C('id') == values['id'])
                               & (C('state').like(values['state']))
                               & (C('create_date') >= as_date(values['start_date']))
                               & (C('create_date') <= as_date(values['end_date']))
                               & (C('template_name').like(values['template_name']))
                               & (C('template_type') == values['template_type'])
                               & (C('organization_id').inner(org_list)))
        if 'id' in list(condition.keys()) and 'is_edit' not in list(condition.keys()):
            # 这样表示查看评估记录模版内容时使用
            _filter.unwind('dataSource')\
                   .add_fields({'assessment_projects': '$dataSource.assessment_projects'})\
                   .lookup_bill('PT_Assessment_Project', 'assessment_projects', 'id', 'ass_info')\
                   .unwind('ass_info')\
                   .project({'_id': 0, 'assessment_projects': 1, 'ass_info': 1})\
                   .project({'ass_info._id': 0})
        else:
            # 这样表示编辑评估模版时使用
            _filter.project({'_id': 0})

        res = self.page_query(_filter, 'PT_Assessment_Template', page, count)
        return res

    def get_assessment_template(self, condition, page, count):
        '''
            获取单条评估模板
            Arguments:
                condition   {dict}      条件
                page        {number}    页码
                count       {number}    条数
        '''
        keys = ['id']
        values = self.get_value(condition, keys)
        # 20190919更新，修改为版本控制查询
        _filter = MongoBillFilter()
        _filter.match_bill(C('id') == values['id'])\
            .project({'_id': 0})
        res = self.page_query(_filter, 'PT_Assessment_Template', page, count)
        print('>>>>>>>>>>>>', res)
        return res

    def update_assessment_template(self, assessment_template):
        '''新增/修改评估模板

        Arguments:
            assessment_template   {dict}      条件
        '''
        # res = 'fail'

        # def process_func(db):
        #     nonlocal res
        #     data = get_info({**assessment_template})
        #     if 'id' in assessment_template.keys():
        #         backVal = update_data(
        #             db, 'PT_Assessment_Template', data, {'id': data['id']})
        #     else:
        #         backVal = insert_data(
        #             db, 'PT_Assessment_Template', data)
        #     if backVal:
        #         res = 'Success'
        # process_db(self.db_addr, self.db_port, self.db_name, process_func)
        # return res

        res = 'fail'

        def process_func(db):
            nonlocal res
            data = get_info({**assessment_template}, self.session)
            print(data, '5555555555555555555555555555555555555')
            if 'id' in assessment_template.keys():
                bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                            TypeId.assessmentTemplate.value, data, 'PT_Assessment_Template')
                if bill_id:
                    res = 'Success'
            else:
                bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                            TypeId.assessmentTemplate.value, data, 'PT_Assessment_Template')
                if bill_id:
                    res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def delete_assessment_template(self, assessment_template_id_list):
        '''删除评估模板接口

        Arguments:
            assessment_template_id_list   {ids}      数据id
        '''
        # res = 'fail'

        # def process_func(db):
        #     nonlocal res
        #     backVal = delete_data(db, 'PT_Assessment_Template', {
        #         'id': assessment_template_id_list[0]})
        #     if backVal:
        #         res = 'Success'
        # process_db(self.db_addr, self.db_port, self.db_name, process_func)
        # return res

        res = 'fail'

        def process_func(db):
            nonlocal res
            ids = []
            if isinstance(assessment_template_id_list, str):
                ids.append(assessment_template_id_list)
            else:
                ids = assessment_template_id_list
            for assessment_template_id in ids:
                # 查询被删除的数据信息
                data = find_data(db, 'PT_Assessment_Template', {
                    'id': assessment_template_id, 'bill_status': 'valid'})
                if len(data) > 0:
                    self.bill_manage_service.add_bill(OperationType.delete.value,
                                                      TypeId.assessmentTemplate.value, data[0], 'PT_Assessment_Template')
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res
